package com.rural.bus.receiver;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.rural.bus.BaseRailwayActivity;
import com.rural.bus.LoginActivity;
import com.rural.bus.MainActivity;
import com.rural.bus.MyApplication;
import com.rural.bus.OrderDetailActivity;
import com.rural.bus.SettingActivity;
import com.rural.bus.WaitActivity;
import com.rural.bus.model.Order;
import com.rural.bus.model.User;
import com.rural.bus.utils.ActivityControl;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则： 1) 默认用户会打开主界面 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
	private static final String TAG = "JPush";

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			Bundle bundle = intent.getExtras();
			// if
			// (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction()))
			// {
			// String regId =
			// bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
			// // Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
			// //send the Registration Id to your server...
			//
			// } else
			if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
				// Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " +
				// bundle.getString(JPushInterface.EXTRA_MESSAGE));
				processCustomMessage(context, bundle);

			}
			// else if
			// (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction()))
			// {
			// // Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
			// int notifactionId =
			// bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
			// // Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
			//
			// } else if
			// (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction()))
			// {
			// // Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
			//
			//
			// } else if
			// (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction()))
			// {
			// Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " +
			// bundle.getString(JPushInterface.EXTRA_EXTRA));
			// //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity，
			// 打开一个网页等..
			//
			// } else
			// if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction()))
			// {
			// boolean connected =
			// intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE,
			// false);
			// Log.w(TAG, "[MyReceiver]" + intent.getAction()
			// +" connected state change to "+connected);
			// } else {
			// Log.d(TAG, "[MyReceiver] Unhandled intent - " +
			// intent.getAction());
			// }
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}

	}

	// send msg to MainActivity
	private void processCustomMessage(Context context, Bundle bundle) {
		String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
		// String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
		Log.d(TAG, "message = " + message);
		try {
			JSONObject object = new JSONObject(message);
			Order order=null;
			try{
				order = Order.parse(object.getJSONObject("order"));
			}catch (JSONException e){
				
			}
//{"order":{"endLatitude":40.20443032344408,"createTime":1454205392000,"startLatitude":40.210435,"orderType":0,"takeTime":1454205360000,"startLocation":"世界城2","remarks":"","perDistance":1.5,"number":1,"driverPhone":"13333333331","orderStatus":2,"carType":0,"groupId":8739109,"endLongtitude":116.3007667285592,"distance":1,"endLocation":"北京洁绿科技发展有限公司","userId":5,"driverId":14,"userName":"jelly","userPhone":"13522761340","estimatePrice":1,"startLongtitude":116.299091,"driverName":"aa(111**111)","orderId":348},"message":"司机到达出发地!","expireTime":300,"action":2}
//{"order":{"endLatitude":40.20443032344408,"createTime":1454205392000,"startLatitude":40.210435,"orderType":0,"takeTime":1454205360000,"startLocation":"世界城2","remarks":"","perDistance":1.5,"number":1,"driverPhone":"13333333331","orderStatus":3,"carType":0,"groupId":8739109,"endLongtitude":116.3007667285592,"distance":1,"endLocation":"北京洁绿科技发展有限公司","userId":5,"driverId":14,"userName":"jelly","userPhone":"13522761340","estimatePrice":1,"startLongtitude":116.299091,"driverName":"aa(111**111)","orderId":348},"message":"上车了祝一路顺风!","expireTime":300,"action":3}
			Log.d("bus", "Push Message:"+ object.toString());
			int action = object.optInt("action", 0);
			OrderDetailActivity.isAutoToPay = false;
			switch (action) {
			case 5:
				// 订单已完成,去支付页
				//{"order":{"endLatitude":40.210451,"createTime":1454206097000,"startLatitude":40.210451,"orderType":0,"takeTime":1454205960000,"startLocation":"世界城2","remarks":"","perDistance":1.5,"number":1,"driverPhone":"13333333331","orderStatus":3,"carType":0,"groupId":8739109,"endLongtitude":116.299126,"distance":1,"endLocation":"企业墅","userId":5,"driverId":14,"userName":"jelly","userPhone":"13522761340","estimatePrice":1.5,"startLongtitude":116.299126,"driverName":"aa(111**111)","orderId":349},"message":"到达目的地请支付!","expireTime":300,"action":5}

				Toast.makeText(MyApplication.instance(), "已到达目的地", Toast.LENGTH_SHORT).show();
				Intent intent1 = new Intent(context, OrderDetailActivity.class);
				intent1.putExtra("order", order);
				OrderDetailActivity.isAutoToPay = true;
				intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent1);
				break;
			case 1:
				// 司机接单了，跳转到订单详情页
				Toast.makeText(MyApplication.instance(), "有司机接单了", Toast.LENGTH_SHORT).show();
				OrderDetailActivity.extra = null;
				Intent intent2 = new Intent(context, OrderDetailActivity.class);
				intent2.putExtra("order", order);
				intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent2);
				break;
			case 9:
				ActivityControl control = ActivityControl.getInstance();
				Activity currentActivity = control.getCurrentActivity();
				User.logout(currentActivity);
				while (!(currentActivity instanceof MainActivity)) {
					
					control.removeActivity(currentActivity);
					currentActivity.finish();
					currentActivity = control.getCurrentActivity();
				}
				Intent intent=new Intent(context, LoginActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
				Toast.makeText(context, "账号在其他设备上登录，请重新登录", Toast.LENGTH_SHORT).show();
				break;
			default:
				// 默认跳转到订单详情页
				OrderDetailActivity.extra = object.getString("message");
				Intent intent3 = new Intent(context, OrderDetailActivity.class);
				intent3.putExtra("order", order);
				intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent3);
				break;
			}

			ActivityControl control = ActivityControl.getInstance();
			Activity currentActivity = control.getCurrentActivity();
			if (currentActivity instanceof WaitActivity) {
				control.removeActivity(currentActivity);
				currentActivity.finish();
			}
			currentActivity = control.getCurrentActivity();
			if (currentActivity instanceof BaseRailwayActivity) {
				control.removeActivity(currentActivity);
				currentActivity.finish();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
